/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.app.hotel.service.impl;

import me.zhengjie.exception.EntityExistException;
import me.zhengjie.modules.app.hotel.domain.HotelInfo;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.app.hotel.repository.HotelInfoRepository;
import me.zhengjie.modules.app.hotel.service.HotelInfoService;
import me.zhengjie.modules.app.hotel.service.dto.HotelFixedAssetsDto;
import me.zhengjie.modules.app.hotel.service.dto.HotelFixedAssetsQueryCriteria;
import me.zhengjie.modules.app.hotel.service.dto.HotelInfoDto;
import me.zhengjie.modules.app.hotel.service.dto.HotelInfoNotInQueryCriteria;
import me.zhengjie.modules.app.hotel.service.dto.HotelInfoQueryCriteria;
import me.zhengjie.modules.app.hotel.service.mapstruct.HotelInfoMapper;
import me.zhengjie.modules.security.service.dto.JwtUserDto;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.RoleRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.dto.UserDto;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;

import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.SecurityUtils;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author Haojie Li
* @date 2021-03-01
**/
@Service
@RequiredArgsConstructor
public class HotelInfoServiceImpl implements HotelInfoService {
	 private final RoleRepository roleRepository;
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final HotelInfoRepository hotelInfoRepository;
    private final HotelInfoMapper hotelInfoMapper;

    @Override
    public Map<String,Object> queryAll(HotelInfoQueryCriteria criteria, Pageable pageable){
    	//获取用户权限
		JwtUserDto jwtUserDto = (JwtUserDto) SecurityUtils.getCurrentUser();
		
		UserDto userDto = jwtUserDto.getUser();
		List<HotelInfoDto> hotelLists = new ArrayList<HotelInfoDto>(userDto.getHotels());
		if(hotelLists.size() == 1) {
			criteria.setId(hotelLists.get(0).getId().toString());
		}
        Page<HotelInfo> page = hotelInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(hotelInfoMapper::toDto));
    }
    @Override
    public Map<String,Object> queryAll(HotelInfoNotInQueryCriteria criteria, Pageable pageable){
    	//获取用户权限
		JwtUserDto jwtUserDto = (JwtUserDto) SecurityUtils.getCurrentUser();
		
		UserDto userDto = jwtUserDto.getUser();
		List<HotelInfoDto> hotelLists = new ArrayList<HotelInfoDto>(userDto.getHotels());
		if(hotelLists.size() == 1) {
			criteria.setId(hotelLists.get(0).getId().toString());
		}
		
		
        Page<HotelInfo> page = hotelInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(hotelInfoMapper::toDto));
    }

    @Override
    public List<HotelInfoDto> queryAll(HotelInfoQueryCriteria criteria){
    	//获取用户权限
		JwtUserDto jwtUserDto = (JwtUserDto) SecurityUtils.getCurrentUser();
		
		UserDto userDto = jwtUserDto.getUser();
		List<HotelInfoDto> hotelLists = new ArrayList<HotelInfoDto>(userDto.getHotels());
		if(hotelLists.size() == 1) {
			criteria.setId(hotelLists.get(0).getId().toString());
		}
        return hotelInfoMapper.toDto(hotelInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public HotelInfoDto findById(String id) {
        HotelInfo hotelInfo = hotelInfoRepository.findById(id).orElseGet(HotelInfo::new);
        ValidationUtil.isNull(hotelInfo.getId(),"HotelInfo","id",id);
        return hotelInfoMapper.toDto(hotelInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HotelInfoDto create(HotelInfo resources) {
    	
    	int length = queryAll(null).size() + 1;
    	resources.setHotelNo(genNo(length));
    	
        resources.setId(IdUtil.simpleUUID()); 
        resources.setCreateBy(SecurityUtils.getCurrentUsername());
        resources.setCreateTime(LocalDateTime.now());
        resources.setIsEnable(1);
        
        HotelInfoDto hotelInfoDto = hotelInfoMapper.toDto(hotelInfoRepository.save(resources));
        
        //创建酒店账号
        User user = new User();
        user.setEnabled(true);
        user.setCreateTime(new Timestamp(new Date().getTime()));
        user.setNickName(hotelInfoDto.getHotelName());
        user.setUsername(hotelInfoDto.getHotelNo());
        user.setCreateBy(SecurityUtils.getCurrentUsername());
        Role role = roleRepository.findById(5L).orElseGet(Role::new);//指定酒店管理员，ID=5
        
        Set<Role> roles = new HashSet<Role>();
        roles.add(role);
        user.setRoles(roles);
        
        Set<HotelInfo> hotels = new HashSet<HotelInfo>();
        hotels.add(hotelInfoRepository.findById(hotelInfoDto.getId()).orElseGet(HotelInfo::new));
        user.setHotels(hotels);
        
        Dept dept = new Dept();
        dept.setId(Long.parseLong(hotelInfoDto.getDeptId()));
        
        user.setDept(dept);
        
        user.setPassword(passwordEncoder.encode("123456"));
        userRepository.save(user);
        return hotelInfoDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(HotelInfo resources) {
    	resources.setUpdateBy(SecurityUtils.getCurrentUsername());
    	resources.setUpdateTime(LocalDateTime.now());
    	
        HotelInfo hotelInfo = hotelInfoRepository.findById(resources.getId()).orElseGet(HotelInfo::new);
        ValidationUtil.isNull( hotelInfo.getId(),"HotelInfo","id",resources.getId());
        hotelInfo.copy(resources);
        hotelInfoRepository.save(hotelInfo);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            hotelInfoRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<HotelInfoDto> all, HttpServletResponse response) throws IOException {
    	DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<Map<String, Object>> list = new ArrayList<>();
        for (HotelInfoDto hotelInfo : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("酒店编号", hotelInfo.getHotelNo());
            map.put("酒店名称", hotelInfo.getHotelName());
            map.put("酒店logo", hotelInfo.getHotelLogo());
            map.put("酒店介绍", hotelInfo.getHotelIntroduce());
            map.put("酒店欢迎语", hotelInfo.getHotelWelcomeWords());
            map.put("酒店欢迎语背景", hotelInfo.getHotelWelcomeWordsBg());
            map.put("创建者", hotelInfo.getCreateBy());
            map.put("更新者", hotelInfo.getUpdateBy());
            map.put("创建时间", hotelInfo.getCreateTime()  == null ? "" : dtf.format(hotelInfo.getCreateTime()));
            map.put("更新时间", hotelInfo.getUpdateTime() == null ? "" : dtf.format(hotelInfo.getUpdateTime()));
             map.put("数据状态", hotelInfo.getIsEnable());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

	@Override
	public HotelInfoDto findByHotelNo(String hotelNo) {
		// TODO Auto-generated method stub
		HotelInfo hotelInfo = hotelInfoRepository.findByHotelNo(hotelNo);
		return hotelInfoMapper.toDto(hotelInfo);
	}

	@Override
	public boolean isExistByHotelNo(String hotelNo) {
		// TODO Auto-generated method stub
		HotelInfo hotelInfo = hotelInfoRepository.findByHotelNo(hotelNo);
		return hotelInfo == null ? false : true;
	}
  public String genNo(int length) {
    	DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyMMdd");
    	
    	DecimalFormat numFormat = new DecimalFormat("000");
    	String no = numFormat.format(length);
    	String startNo = LocalDate.now().format(dtf);
    	startNo = startNo + no;
    	
    	//判定是否存在
    	HotelInfoQueryCriteria criteria = new HotelInfoQueryCriteria();
    	criteria.setHotelNo(startNo);
    	List<HotelInfoDto> tempList = queryAll(criteria);
    	if(tempList != null && tempList.size() > 0) {
    		length += 1;
    		return genNo(length);
    	}
    	return startNo;
    }
}